using System.Collections.Generic;

using NHibernate;
using NHibernate.Expression;

using Wayloop.Fusion.Core.DataAccess;
using Wayloop.Fusion.Data.HttpModules;

namespace Wayloop.Fusion.Data
{
    public abstract class BaseDao<T, IdT> : IDao<T, IdT>
    {
        protected ISession DataSession
        {
            get { return NHibernateSessionManager.Session; }
        }


        public T GetById(IdT id)
        {
            return DataSession.Get<T>(id);
        }


        public List<T> GetAll()
        {
            return GetByCriteria();
        }


        public T Save(T entity)
        {
            DataSession.Save(entity);

            return entity;
        }


        public T SaveOrUpdate(T entity)
        {
            DataSession.SaveOrUpdate(entity);

            return entity;
        }


        public void Delete(T entity)
        {
            DataSession.Delete(entity);
        }


        public void CommitChanges()
        {
            DataSession.Flush();
        }


        protected List<T> GetByCriteria(params ICriterion[] expressions)
        {
            return CreateCriteria(expressions).List<T>() as List<T>;
        }


        protected T GetUniqueByCriteria(params ICriterion[] expressions)
        {
            return CreateCriteria(expressions).UniqueResult<T>();
        }


        private ICriteria CreateCriteria(params ICriterion[] expressions)
        {
            ICriteria criteria = DataSession.CreateCriteria(typeof (T));

            foreach (ICriterion expression in expressions)
                criteria.Add(expression);

            return criteria;
        }
    }
}